package com.itheima.stargraph.job;

import com.itheima.stargraph.api.ComfyuiApi;
import com.itheima.stargraph.pojo.ComfyuiTask;
import com.itheima.stargraph.service.Text2ImageService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;

/**
 * 定时添加Comfyui工作流任务的定时任务
 *
 * @Author mr.zhang
 * Date 2025/6/12 8:53
 */
@Component
@Slf4j
public class RunWorkflowTaskJob {

    @Autowired
    private Text2ImageService text2ImageService;
    @Autowired
    private ComfyuiApi comfyuiApi;

    //锁缓存的键
    private static final String REDIS_KEY_TASK_LOCK = "star:graph:task:lock";
    @Autowired
    private RedissonClient redissonClient;//Redisson客户端对象

    @Scheduled(cron = "*/10 * * * * ?")
    public void runWorkflowTask(){
        //1.获取锁对象
        RLock lock = redissonClient.getLock(REDIS_KEY_TASK_LOCK);
        //2.尝试加锁
        boolean result = lock.tryLock();
        //3.加锁失败,拒绝执行
        if (!result){
            log.error("加锁失败,拒绝执行");
            return;
        }
        //4.成功,执行
        try {
            //1. 从Redis队列获取最优先执行的任务
            ComfyuiTask comfyuiTask = text2ImageService.popComfyuiTask();
            if(comfyuiTask==null) {
                return;
            }

            //2. 调用comfyui的API添加流程任务
            Call<HashMap> call = comfyuiApi.addQueueTask(comfyuiTask.getComfyuiRequestDto());

            //3. 获取comfyui添加流程任务的响应结果
            Response<HashMap> response = call.execute();
            if(!response.isSuccessful()) {
                log.error("[文生图定时任务-添加comfyui任务]任务添加失败");
                return;
            }

            String promptId = String.valueOf(response.body().get("prompt_id"));
            log.info("[文生图定时任务-添加comfyui任务]任务添加完毕，任务id:{}, promptId:{}",comfyuiTask.getId(), promptId);

            //4.缓存promptId与clientId的对应关系(实际上是缓存promptId与ComfyuiTask的对应关系)
            text2ImageService.addStartedTask(promptId,comfyuiTask);

        }  catch (IOException e) {
            log.error("[文生图定时任务-添加comfyui任务]任务添加异常：", e);
        } finally {
            //5. 执行完业务释放锁
            lock.unlock();
        }


    }
}
